package util

import (
	"likeadmin/config"
	"likeadmin/core"
	"net/url"
	"path"
	"strings"
)

var (
	UrlUtil      = urlUtil{}
	publicUrl    = config.Config.PublicUrl
	publicPrefix = config.Config.PublicPrefix
)

// urlUtil 文件路径处理工具
type urlUtil struct{}

// ToAbsoluteUrl 转绝对路径
func (uu urlUtil) ToAbsoluteUrl(u string) string {
	//获取默认的存储engine
	engine := SettingUtil.GetStorageEngine()

	if u == "" {
		return ""
	}

	up, err := url.Parse(publicUrl)
	if err != nil {
		core.Logger.Errorf("ToAbsoluteUrl Parse err: err=[%+v]", err)
		return u
	}
	// 如果是系统默认的图片
	if strings.HasPrefix(u, "/api/static/") {
		up.Path = path.Join(up.Path, u)
		return up.String()
	}

	if engine == "local" {

		up.Path = path.Join(up.Path, publicPrefix, u)
		return up.String()

	} else if engine == "aliyun" {

		conf := SettingUtil.GetStorageEngineConf("aliyun")
		up, err = url.Parse(conf.Domain)
		if err != nil {
			core.Logger.Errorf("ToAbsoluteUrl Parse aliyun err: err=[%+v]", err)
			return u
		}
		up.Path = path.Join(up.Path, u)
		return up.String()

	} else if engine == "qcloud" {

		conf := SettingUtil.GetStorageEngineConf("qcloud")
		up, err = url.Parse(conf.Domain)
		if err != nil {
			core.Logger.Errorf("ToAbsoluteUrl Parse qcloud err: err=[%+v]", err)
			return u
		}
		up.Path = path.Join(up.Path, u)
		return up.String()

	} else if engine == "qiniu" {

		conf := SettingUtil.GetStorageEngineConf("qiniu")
		up, err = url.Parse(conf.Domain)
		if err != nil {
			core.Logger.Errorf("ToAbsoluteUrl Parse qiniu err: err=[%+v]", err)
			return u
		}
		up.Path = path.Join(up.Path, u)
		return up.String()

	}

	return u
}

// ToRelativeUrl 还原成相对路径
func (uu urlUtil) ToRelativeUrl(u string) string {
	//获取默认的存储engine
	engine := SettingUtil.GetStorageEngine()

	if u == "" {
		return ""
	}
	up, err := url.Parse(u)
	if err != nil {
		core.Logger.Errorf("ToRelativeUrl Parse err: err=[%+v]", err)
		return u
	}

	lu := up.String()
	if engine == "local" {
		return strings.Replace(
			strings.Replace(lu, publicUrl, "", 1),
			publicPrefix, "", 1)
	} else if engine == "aliyun" {
		conf := SettingUtil.GetStorageEngineConf("aliyun")
		return strings.Replace(lu, conf.Domain, "", 1)
	} else if engine == "qcloud" {
		conf := SettingUtil.GetStorageEngineConf("qcloud")
		return strings.Replace(lu, conf.Domain, "", 1)
	} else if engine == "qiniu" {
		conf := SettingUtil.GetStorageEngineConf("qiniu")
		return strings.Replace(lu, conf.Domain, "", 1)
	}

	return u
}
